import re
import jsonpath
from Common.handle_config import conf
from Common.my_logger import logger


# 动态类属性(环境变量）
class EnvData:
    """
    储存用例需要的数据
    """
    pass


# 列表参数处理
def __setSubJectScoreInfos(data):
    setSubJectScoreInfos = []
    for li in data:
        ll = {}
        ll['queNo'] = li['queNo']
        ll['scoreValue'] = int(li['scoreValue'])
        ll['stepValue'] = int(li['stepValue'])
        setSubJectScoreInfos.append(ll)
    setattr(EnvData, "setSubJectScoreInfos", setSubJectScoreInfos)


# 正则数据替换
def __replace_by_regular(data):
    res = re.findall("#(.*?)#", data)
    # 如果没用找到返回空列表
    # 标识符对应的值，来自：1.环境变量（EnvData） 2.配置文件
    if res:
        for item in res:
            try:
                value = getattr(EnvData, item)
                logger.info('从环境变量EnvData类当中获取需要传递数据:{}={}'.format(item, value))
            except:
                value = conf.get('EnvData', item)
                logger.info('从配置文件data当中获取需要传递数据:{}={}'.format(item, value))
            print(item, '==', value)
            data = data.replace("#{}#".format(item), str(value))
    return data


# 把Excel当中提取出来的测试数据进行数据替换
def replace_case_by_regular(case):
    """
    把Excel当中提取出来的测试数据进行数据替换
    """
    for key, value in case.items():
        if value is not None and isinstance(value, str):
            case[key] = __replace_by_regular(value)
    return case


# 数据替换（暂时不用）
def replace_mark_with_data(case, mark, real_data):
    """
    :param case: excel中读取到的数据
    :param mark: 数据中的占位符：#****#（被替换数据）
    :param real_data: 替换Mark中的真实数据
    :return:
    """
    for key, value in case.items():
        if case[key] is not None and isinstance(case[key], str):  # 确保是个字符串
            if value.find(mark) != -1:  # 确保找到标识符
                case[key] = value.replace(mark, real_data)
    return case


# 数据替换（替换extract_data内的数据）
def replace_extract_data(case, requests):
    '''

    :param case: excel中读取到的数据
    :param requests: 请求返回的结果
    :return:
    '''
    # if  isinstance(case,str):

    if case is not None:
        if isinstance(case, str):
            case = eval(case)
            for key, value in case.items():
                # logger.info('获取到需要替换的数据:{}={}并添加到环境变量'.format(key, jsonpath.jsonpath(requests.json(), value)[0]))

                setattr(EnvData, key, jsonpath.jsonpath(requests.json(), value)[0])
                # 特殊处理，对于多个需要不定长度参数添加环境变量
                if isinstance(jsonpath.jsonpath(requests.json(), value)[0], list):
                    __setSubJectScoreInfos(jsonpath.jsonpath(requests.json(), value)[0])
        elif isinstance(case, dict):
            for key, value in case.items():
                # logger.info('获取到需要替换的数据:{}={}并添加到环境变量'.format(key, jsonpath.jsonpath(requests.json(), value)[0]))

                setattr(EnvData, key, jsonpath.jsonpath(requests.json(), value)[0])
                # 特殊处理，对于多个需要不定长度参数添加环境变量
                if isinstance(jsonpath.jsonpath(requests.json(), value)[0], list):
                    __setSubJectScoreInfos(jsonpath.jsonpath(requests.json(), value)[0])


# 清理EnvData里设置的属性
def clear_EnvData_attrs():
    values = dict(EnvData.__dict__.items())
    for key, value in values.items():
        if key.startswith('__'):
            pass
        else:
            delattr(EnvData, key)
            logger.info('清空EnvData类当中的环境变量')


if __name__ == '__main__':
    case = {'id': 1, 'tile': '登录成功', 'method': 'POST', 'url': '/M/login',
            'data': '{"userPassword":"wang199621com","userPhone":"#userPhone#"}',
            'expected': "{'code': 200, 'msg': 'ok'}",
            'check_sql': 'SELECT userPhone FROM `user` WHERE userPhone = "15237531610"'}
    case0 = {'id': 1, 'tile': '登录成功', 'method': 'POST', 'url': '/M/login',
             'data': '{"userPassword":"wang199621com","userPhone":"#userPhone#"}',
             'expected': "{'code': 200, 'msg': 'ok'}",
             'check_sql': 'SELECT userPhone FROM `user` WHERE userPhone = "15237531610"'}
    case1 = {'id': 1, 'tile': '登录成功', 'method': 'POST', 'url': '/M/login',
             'data': '{"userPassword":"#userPassword#","userPhone":"15237531611"}',
             'expected': "{'code': 200, 'msg': 'ok'}",
             'check_sql': 'SELECT userPhone FROM `user` WHERE userPhone = "15237531610"'}
    data1 = {"userPassword": "#userPassword#", "Token": "#userPhone#"}
    dat = '{"userPassword":"#userPassword#","userPhone":"#userPhone#"}'
    phone = '15237531610'
    # if case['data'].find('#phone#'):
    #     print("找到了")
    # s = replace_mark_with_data(case, "#userPhone#", phone)
    # print(s)
    EnvData()
    # print(case0)
    # setattr(EnvData, 'userPhone', phone)
    # values = dict(EnvData.__dict__.items())
    # data = replace_case_by_regular(case0)
    # print(data)
    data = {"token": "Token"}
    # data = eval(case['extract_data'])
    print(''.join(jsonpath.jsonpath(data1, '$..Token')))
